<template>
    <div class="inbound-form-container">
        <el-card header="新增出库">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="inbound-form">
                <!-- 疫苗选择 -->
                <el-form-item label="疫苗选择" prop="vaccineId">
                    <el-select v-model="form.vaccineId" placeholder="请选择疫苗" filterable style="width: 100%"
                        @change="handleVaccineChange">
                        <el-option v-for="vaccine in vaccineList" :key="vaccine.id" :label="vaccine.vaccineName"
                            :value="vaccine.id" />
                    </el-select>
                </el-form-item>

                <!-- 批次号 -->
                <!-- <el-form-item label="批次号" prop="batchNumber">
                    <el-input v-model="form.batchNumber" placeholder="请输入批次号" maxlength="50" />
                </el-form-item> -->

                <!-- 入库数量 -->
                <el-form-item label="出库数量" prop="quantity">
                    <el-input-number v-model="form.quantity" :min="1" :max="10000" placeholder="请输入出库数量"
                        style="width: 100%" />
                </el-form-item>


                <el-form-item label="接种人" prop="recipientName">
                    <el-input v-model="form.recipientName" placeholder="请输入接种人" maxlength="100" />
                </el-form-item> <!-- 用途 -->
                <el-form-item label="身份证号" prop="recipientIdcard">
                    <el-input v-model="form.recipientIdcard" placeholder="请输入身份证" maxlength="100" />
                </el-form-item>
                <!-- 用途 -->
                <el-form-item label="用途" prop="purpose">
                    <el-input v-model="form.purpose" placeholder="请输入用途" maxlength="100" />
                </el-form-item>

                <!-- 出库备注 -->
                <el-form-item label="出库备注" prop="remark">
                    <el-input v-model="form.remark"  type="textarea" :rows="3" placeholder="请输入出库备注信息" maxlength="200"
                        show-word-limit />
                </el-form-item>

                <!-- 操作按钮 -->
                <el-form-item class="form-actions">
                    <el-button type="primary" @click="handleSubmit" :loading="loading">
                        提交出库
                    </el-button>
                    <el-button @click="handleReset">重置</el-button>
                    <el-button @click="handleCancel">取消</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

// 表单数据
const form = reactive({
    vaccineId: '',
    // batchNumber: '',
    quantity: 1,
    recipientName: '',
    recipientIdcard: '',
    purpose: '',
    remark: ''
})

// 表单验证规则
const rules = reactive({
    vaccineId: [
        { required: true, message: '请选择疫苗', trigger: 'change' }
    ],
    // batchNumber: [
    //     { required: true, message: '请输入批次号', trigger: 'blur' }
    // ],
    quantity: [
        { required: true, message: '请输入入库数量', trigger: 'blur' },
        { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
    ],

    purpose: [
        { required: true, message: '请输入用途', trigger: 'blur' }
    ]
})

// 疫苗列表
const vaccineList = ref([])
const loading = ref(false)
const formRef = ref()

// 加载疫苗列表
const loadVaccineList = async () => {
    try {
        axios.get("http://127.0.0.1:8081/vaccine/list", {
            headers: {
                'X-Admin-Token': sessionStorage.getItem("token")
            },
            params: {
                page: 1,
                size: 300,
            }
        }).then((req) => {
            vaccineList.value = req.data.Data
        })

    } catch (error) {
        ElMessage.error('加载疫苗列表失败')
        console.error('加载疫苗列表失败:', error)
    }
}

// 疫苗选择变化
const handleVaccineChange = (vaccineId) => {
    console.log('选择的疫苗ID:', vaccineId)
}

// 提交表单
const handleSubmit = async () => {
    try {
        // 表单验证
        await formRef.value.validate()

        // 日期验证
        if (form.productionDate && form.expiryDate) {
            const production = new Date(form.productionDate)
            const expiry = new Date(form.expiryDate)
            if (production >= expiry) {
                ElMessage.error('有效期必须晚于生产日期')
                return
            }
        }
        loading.value = true
        // 使用axios提交入库数据
        axios.post("http://127.0.0.1:8081/vaccine/outbound/add", form, {
            headers: {
                'X-Admin-Token': sessionStorage.getItem("token")
            }
        }).then((req) => {
            if (req.data.success === true) {
                ElNotification({
                    message: req.data.message,
                    type: "success",
                    position: 'bottom-right',
                })
                handleReset()
            }
        })

    } catch (error) {
        if (error.errors) {
            // 表单验证失败
            return
        }
        ElMessage.error('出库失败：' + (error.message || '未知错误'))
        console.error('出库失败:', error)
    } finally {
        loading.value = false
    }
}

// 重置表单
const handleReset = () => {
    formRef.value.resetFields()
    form.quantity = 1
}

// 取消操作
const handleCancel = () => {
    ElMessageBox.confirm('确定要取消出库吗？未保存的数据将会丢失。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        router.back()
    })
}

// 页面加载时获取疫苗列表
onMounted(() => {
    loadVaccineList()
})
</script>

<style scoped>
.inbound-form-container {
    padding: 20px;
    max-width: 100%;
    margin: 0 auto;
}

.inbound-form {
    max-width: 100%;
}

.form-actions {
    margin-top: 30px;
    text-align: center;
}

:deep(.el-card__header) {
    background: #f5f7fa;
    font-weight: bold;
}
</style>